package com.zjb.demo.common.controller;

import com.zjb.demo.common.constant.CacheConstants;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.system.domain.SysCache;
import io.swagger.annotations.Api;
import org.noear.redisx.plus.RedisBucket;
import org.noear.solon.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 缓存监控
 *
 * @author 庄佳彬
 * @since 2023/12/26 22:52
 */
@Controller
@Api(tags = "缓存监控")
@Mapping("/monitor/cache")
public class CacheController {
    private final static List<SysCache> caches = new ArrayList<>();

    static {
        caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
        caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
        caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
        caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
        caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
    }

    @Inject
    private RedisBucket redisBucket;

//    @Get
//    @Mapping
//    public AjaxResult<List<SysCache>> list() {
//        redisClient.
//        return new AjaxResult<>(caches);
//    }

    @Get
    @Mapping("/getNames")
    public AjaxResult<List<SysCache>> list() {
        return AjaxResult.success(caches);
    }

    @Get
    @Mapping("/getKeys/{cacheName}")
    public AjaxResult<Set<String>> getCacheKeys(String cacheName) {
        return AjaxResult.success(redisBucket.keys(cacheName));
    }

    @Get
    @Mapping("/getValue/{cacheName}/{cacheKey}")
    public AjaxResult<SysCache> getCacheValue(String cacheName, String cacheKey) {
        var str = redisBucket.get(cacheKey);
        return AjaxResult.success(new SysCache(cacheName, cacheKey, str));
    }

    @Delete
    @Mapping("/clearCacheName/{cacheName}")
    public AjaxResult<Void> clearCacheName(String cacheName) {
        Collection<String> cacheKeys = redisBucket.keys(cacheName + "*");
        redisBucket.remove(cacheKeys);
        return AjaxResult.success();
    }

    @Delete
    @Mapping("/clearCacheKey/{cacheKey}")
    public AjaxResult<Void> clearCacheKey(String cacheKey) {
        redisBucket.remove(cacheKey);
        return AjaxResult.success();
    }

    @Delete
    @Mapping("/clearCacheAll")
    public AjaxResult<Void> clearCacheAll() {
        Collection<String> cacheKeys = redisBucket.keys("*");
        redisBucket.remove(cacheKeys);
        return AjaxResult.success();
    }

}
